package com.pmgames.store
{
	import com.pmgames.store.events.JavaFlexBoundaryConditionEvent;
	import com.pmgames.store.events.JavaFlexLoseEvent;
	import com.pmgames.store.events.JavaFlexWinEvent;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;

	public class GuessedWord extends EventDispatcher
	{
		private var guessedWord:ArrayCollection, wordToGuess:String;
		private var lettersToOpen:int, tryNumber:int, stepsBeforeLose:int;
		
		public function setGuessedWord(value:String):void
		{
			for(var index:int = 0; index < value.length; index++)
			{
				guessedWord.addItem(value.charAt(index));
			}
		}
				
		public function getGuessedWord():String
		{
			return guessedWord.toString();
		}	
		
		public function setWordToGuess(value:String):void
		{
			wordToGuess = value;
		}
				
		public function getWordToGuess():String
		{
			return wordToGuess;
		}		
		
		public function setLettersToOpen(value:int):void
		{
			lettersToOpen = value;
		}	
		
		public function getLettersToOpen():int
		{
			return lettersToOpen;
		}		
		
		public function setTryNumber(value:int):void
		{
			tryNumber = value;
		}	
		
		public function getTryNumber():int
		{
			return tryNumber;
		}		
		
		public function GuessedWord(wordToGuessVal:String = "", stepsBeforeLoseVal:int):void
		{
			wordToGuess = wordToGuessVal;
			guessedWord = new ArrayCollection();
			lettersToOpen = 0;
			tryNumber = 1;
			stepsBeforeLose = stepsBeforeLoseVal;
		}
		
		public function addLetterToWord(letter:String, index:int):void
		{
			guessedWord.addItemAt(letter, index);
			lettersToOpen++;
			if(lettersToOpen >= wordToGuess.length)
			{
				tryNumber++;
				setSpecialSymbols();
				if(guessedWord.toString() == wordToGuess)
				{
					dispatchEvent(JavaFlexWinEvent.WORD_GUESSED);
				}
				else
				{
					if(tryNumber > stepsBeforeLose)
					{
						dispatchEvent(JavaFlexLoseEvent.WORD_NOT_GUESSED);
					}
					else
					{
						dispatchEvent(JavaFlexBoundaryConditionEvent.BOUNDARY_CONDITION);
					}
				}
			}
		}
		
		private function setSpecialSymbols():void
		{
			for(var index:int = 0; index < wordToGuess.length; index++)
			{
				if(wordToGuess.charAt(index) < 'A' || wordToGuess.charAt(index) > 'z')
				{
					guessedWord.addItemAt(wordToGuess.charAt(index), index);
				}
			}
		}
		
		public function resetWord():void
		{
			this();
		}
		
	}
}